class CountArray { public static void main ( String[] args ) { int[] egArray = { 2, 4, 6, 8, 10, 1, 3, 5, 7, 9 }; for ( int index= 0 ; index < 10 ; index++ ) { System.out.println( egArray[ index ] ); } } }
length
of an ArrayIt is annoying to count the elements in an array. Worse, when you write your program you may not be able to count the elements. Often, array objects are created as the program is running. Often, the length of the array depends on data. You need to write programs that can deal with arrays whose sizes are not known until the program is running.
Luckily, your program can ask the array how many elements it has.
Remember that an array is an object.
As an object, it has more in it than just the slots.
An array object has a member length
that is the number of
slots (number of elements) it has.
The for
statement can be written like this:
for ( int index= 0 ; index < egArray.length; index++ )
Lines of code similar to the above are very common in programs. Programs often uses several arrays, and frequently need to "visit" each element of their arrays.